package com.lkd.shoppingcart.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lkd.shoppingcart.entity.Page;
import com.lkd.shoppingcart.entity.Product;
import com.lkd.shoppingcart.service.ProductService;
import com.lkd.shoppingcart.service.impl.ProductServiceImpl;
import com.lkd.shoppingcart.utils.WebUtils;

@WebServlet("/client/productServlet")
public class ClientProductServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;
	private ProductService productService = new ProductServiceImpl();

	/**
	 * 获取页面信息
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
		int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
		Page<Product> page = productService.page(pageNo, pageSize);
		page.setUrl("client/productServlet?action=page");
		req.setAttribute("page", page);
		req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);
	}

	/**
	 * 根据价格区间获取页面信息
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
		int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
		int min = WebUtils.parseInt(req.getParameter("min"), 0);
		int max = WebUtils.parseInt(req.getParameter("max"), Integer.MAX_VALUE);

		Page<Product> page = productService.pageByPrice(pageNo, pageSize, min, max);

		StringBuilder sb = new StringBuilder("client/productServlet?action=pageByPrice");
		
		// 如果有最小价格的参数,追加到分页条的地址参数中
		if (req.getParameter("min") != null) {
			sb.append("&min=").append(req.getParameter("min"));
		}
		
		// 如果有最大价格的参数,追加到分页条的地址参数中
		if (req.getParameter("max") != null) {
			sb.append("&max=").append(req.getParameter("max"));
		}
		
		page.setUrl(sb.toString());
		
		req.setAttribute("page", page);
		req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);
	}
	
}
